package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.Report;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.NewsReport;
import com.ruoyi.system.service.INewsReportService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 舆情报告Controller
 * 
 * @author shan
 * @date 2025-02-28
 */
@RestController
@RequestMapping("/system/report")
public class NewsReportController extends BaseController
{
    @Autowired
    private INewsReportService newsReportService;

    @Autowired
    private MarkdownToWord markdownToWord;
    @Autowired
    private BotChatCompletionsExample botChatCompletionsExample;

    /**
     * 查询舆情报告列表
     */
    @PreAuthorize("@ss.hasPermi('system:report:list')")
    @GetMapping("/list")
    public TableDataInfo list(NewsReport newsReport)
    {
        startPage();
        List<NewsReport> list = newsReportService.selectNewsReportList(newsReport);
        return getDataTable(list);
    }

    /**
     * 导出舆情报告列表
     */
    @PreAuthorize("@ss.hasPermi('system:report:export')")
    @Log(title = "舆情报告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NewsReport newsReport)
    {
        List<NewsReport> list = newsReportService.selectNewsReportList(newsReport);
        ExcelUtil<NewsReport> util = new ExcelUtil<NewsReport>(NewsReport.class);
        util.exportExcel(response, list, "舆情报告数据");
    }

    /**
     * 获取舆情报告详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:report:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(newsReportService.selectNewsReportById(id));
    }

    /**
     * 新增舆情报告
     */
    @PreAuthorize("@ss.hasPermi('system:report:add')")
    @Log(title = "舆情报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody NewsReport newsReport)
    {
        String reportWord = botChatCompletionsExample.getReport(newsReport.getCaseName());
        String filePath = markdownToWord.saveWord(newsReport.getCaseName(), reportWord);
        newsReport.setFile(filePath);
        newsReport.setCreateBy(getUsername());
        return toAjax(newsReportService.insertNewsReport(newsReport));
    }

    /**
     * 新增舆情报告
     */
    @PreAuthorize("@ss.hasPermi('system:report:add')")
    @Log(title = "舆情报告2", businessType = BusinessType.INSERT)
    @PostMapping("/add2")
    public Map<String, String> add2(@RequestBody NewsReport newsReport)
    {
        String reportWord = botChatCompletionsExample.getReport(newsReport.getCaseName());
        String filePath = markdownToWord.saveWord(newsReport.getCaseName(), reportWord);
        newsReport.setFile(filePath);
        newsReport.setCreateBy(getUsername());
        newsReportService.insertNewsReport(newsReport);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("data", reportWord);
        return stringStringHashMap;
    }

    /**
     * 修改舆情报告
     */
    @PreAuthorize("@ss.hasPermi('system:report:edit')")
    @Log(title = "舆情报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody NewsReport newsReport)
    {
        return toAjax(newsReportService.updateNewsReport(newsReport));
    }

    /**
     * 删除舆情报告
     */
    @PreAuthorize("@ss.hasPermi('system:report:remove')")
    @Log(title = "舆情报告", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(newsReportService.deleteNewsReportByIds(ids));
    }

    // 计算 Levenshtein 距离
    private static int levenshteinDistance(String s1, String s2) {
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];

        for (int i = 0; i <= s1.length(); i++) {
            for (int j = 0; j <= s2.length(); j++) {
                if (i == 0) {
                    dp[i][j] = j;
                } else if (j == 0) {
                    dp[i][j] = i;
                } else {
                    dp[i][j] = Math.min(
                            Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1),
                            dp[i - 1][j - 1] + (s1.charAt(i - 1) == s2.charAt(j - 1) ? 0 : 1)
                    );
                }
            }
        }

        return dp[s1.length()][s2.length()];
    }

    // 计算相似度，距离越小相似度越高
    private static double similarity(String s1, String s2) {
        int distance = levenshteinDistance(s1, s2);
        int maxLength = Math.max(s1.length(), s2.length());
        return 1.0 - (double) distance / maxLength;
    }

    // 根据案件名称查找最相似的报告并返回报告名称
    public static String findMostSimilarReportName(String caseName, List<Report> reports) {
        Report mostSimilarReport = null;
        double maxSimilarity = 0;

        for (Report report : reports) {
            double similarity = similarity(caseName, report.getTitle());
            if (similarity > maxSimilarity) {
                maxSimilarity = similarity;
                mostSimilarReport = report;
            }
        }

        return mostSimilarReport != null ? mostSimilarReport.getTitle() : null;
    }

    private String  getReport(String report) {
        // 模拟数据库中的报告数据
        List<Report> reports = new ArrayList<>();
        reports.add(new Report("类型1", "报告1标题", "报告1内容"));
        reports.add(new Report("类型2", "报告2标题", "报告2内容"));
        reports.add(new Report("类型3", "报告3标题", "报告3内容"));

        // 输入案件名称
        String caseName = "案件名称示例";

        // 调用函数查找最相似的报告名称
        String mostSimilarReportName = findMostSimilarReportName(caseName, reports);

        if (mostSimilarReportName != null) {
            System.out.println("最相似的报告名称: " + mostSimilarReportName);
            return mostSimilarReportName;
        } else {
            System.out.println("未找到相似的报告。");
        }
        return null;
    }

}
